package cn.lpq.one_qrcode_pay.handlers;

import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.egzosn.pay.common.util.str.StringUtils;
import com.egzosn.pay.wx.bean.WxPayMessage;

import cn.lpq.one_qrcode_pay.model.WechatPayDetail;
import cn.lpq.one_qrcode_pay.service.WechatPayDetailService;
import cn.lpq.one_qrcode_pay.util.HttpUtil;

/**
 * 微信支付回调处理器 Created by ZaoSheng on 2016/6/1.
 */
@Component
public class WxPayMessageHandler implements PayMessageHandler<WxPayMessage, PayService> {

	@Resource
	private WechatPayDetailService thisService;

	@Override
	public PayOutMessage handle(WxPayMessage payMessage, Map<String, Object> context, PayService payService)
			throws PayErrorException {
		// 交易状态
		if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))) {
			// 这里进行成功的处理
			WechatPayDetail payDetail = thisService.getById(payMessage.getOutTradeNo());
			payDetail.setUpdateTime(new Date());
			payDetail.setPayTime(payMessage.getTimeEnd());
			payDetail.setPayStatus(true);
			payDetail.setBankSn(payMessage.getTransactionId());
			boolean flag = thisService.updateById(payDetail);
			if (flag) {
				if (StringUtils.isNotEmpty(payMessage.getAttach())) {
					JSONObject jsonObject = JSONObject.parseObject(payMessage.getAttach());
//					try {
//						// 向前端发送已支付的信息
//						WebSocketServer.sendInfo("PAID", jsonObject.get("timestamp").toString());
//					} catch (IOException e) {
//					}

					String callBackUrl = jsonObject.getString("callBackUrl");
					callBackUrl = URLDecoder.decode(callBackUrl);
					HttpUtil.init().get(callBackUrl);
				}
				return payService.getPayOutMessage("SUCCESS", "OK");
			}else {
				return payService.getPayOutMessage("FAIL", "失败");
			}
		}

		return payService.getPayOutMessage("FAIL", "失败");
	}
}
